﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace LibrarySystem
{
    public partial class WebForm5 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string _val = Request.QueryString["val"];
            string _term = Server.UrlDecode(Request.QueryString["term"]);
            _term = _term.Replace(" ", "%");
            
            if (_val != "")
            {
                if (_val == "Title") {
                    Global.SearchResultList = BusinessLayer.Book.searchByISBNorTitle(_val, _term);
                }
                else if (_val == "Author") {
                    Global.SearchResultList = BusinessLayer.Book.getByAuthorName(_term);
                }
                else if (_val == "ISBN") {
                    Global.SearchResultList = BusinessLayer.Book.searchByISBNorTitle(_val, _term);
                }

                Global.SearchResultList = Global.SearchResultList.OrderBy(o => o.Title).ToList();
                Global.SearchResultList = Global.SearchResultList.GroupBy(o => o.Title).Select(o => o.First()).ToList();
                searchResList.DataSource = Global.SearchResultList;
                searchResList.DataBind();
                searchResCount.Text = "Antal träffar: " + Global.SearchResultList.Count;
            }
        }

        protected void DataPager_PreRender(object sender, EventArgs e)
        {
            searchResList.DataSource = Global.SearchResultList;
            searchResList.DataBind();
        }

        protected void searchResList_DataBound(object sender, EventArgs e)
        {
            DataPager1.Visible = (DataPager1.PageSize < DataPager1.TotalRowCount);
            DataPager2.Visible = (DataPager2.PageSize < DataPager2.TotalRowCount);
        }

        protected void listItem_Clicked(object sender, CommandEventArgs e)
        {
            string itemISBN = e.CommandName.ToString();
            Response.Redirect("bookDetailPage.aspx?isbn=" + itemISBN);
        }
    }
}